package com.jarvis.hospital.prescription;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jarvis.hospital.R;
import com.jarvis.hospital.common.BaseActivity;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.contants.ContactModel;
import com.jarvis.hospital.login.model.LoginModel;
import com.jarvis.hospital.login.model.UserModel;
import com.jarvis.hospital.patient.PatientChooseActivity;
import com.jarvis.hospital.prescription.adapter.BloodTimeAdapter;
import com.jarvis.hospital.prescription.adapter.CFDurationAdapter;
import com.jarvis.hospital.prescription.adapter.MTXDurationAdapter;
import com.jarvis.hospital.prescription.model.AddNewPrescriptionRequestModel;
import com.jarvis.hospital.prescription.model.BloodIntervalListModel;
import com.jarvis.hospital.prescription.model.BloodTimeModel;
import com.jarvis.hospital.prescription.model.CFIntervalListModel;
import com.jarvis.hospital.prescription.model.CFIntervalModel;
import com.jarvis.hospital.prescription.model.DefaultPrescriptionModel;
import com.jarvis.hospital.prescription.model.EditPrescriptionRequestModel;
import com.jarvis.hospital.prescription.model.PerfusionIntervalListModel;
import com.jarvis.hospital.prescription.model.PerfusionIntervalModel;
import com.jarvis.hospital.prescription.model.PrescriptionInfoDetailModel;
import com.jarvis.hospital.prescription.model.PrescriptionInfoModel;
import com.jarvis.hospital.prescription.model.ProgrammeInfoModel;
import com.jarvis.hospital.servers.ApiService;
import com.jarvis.hospital.util.DividerItemDecoration;
import com.jarvis.hospital.util.SharePreferenceKey;
import com.jarvis.hospital.util.SharePreferenceUtils;
import com.jarvis.hospital.util.net.RequestApi;
import com.jarvis.hospital.widget.ScrollGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class NewPrescriptionActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.rel_left)
    RelativeLayout rel_left;
    @BindView(R.id.rel_right)
    RelativeLayout rel_right;
    @BindView(R.id.tv_right)
    TextView tv_right;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_choose_patient)
    TextView tv_choose_patient;
    @BindView(R.id.tv_patient_name)
    TextView tv_patient_name;
    @BindView(R.id.tv_patient_sex)
    TextView tv_patient_sex;
    @BindView(R.id.tv_patient_bed_no)
    TextView tv_patient_bed_no;
    @BindView(R.id.tv_patient_history)
    TextView tv_patient_history;
    @BindView(R.id.tv_patient_age)
    TextView tv_patient_age;
    @BindView(R.id.tv_patient_weight)
    TextView tv_patient_weight;
    @BindView(R.id.tv_patient_height)
    TextView tv_patient_height;

    @BindView(R.id.tv_MTXdose)
    TextView tv_MTXdose;
    @BindView(R.id.rel_MTXdose)
    RelativeLayout rel_MTXdose;
    @BindView(R.id.tv_MTXDuration)
    TextView tv_MTXDuration;
    @BindView(R.id.rel_MTXDuration)
    RelativeLayout rel_MTXDuration;
    @BindView(R.id.tv_CFdose)
    TextView tv_CFdose;
    @BindView(R.id.rel_CFdose)
    RelativeLayout rel_CFdose;
    @BindView(R.id.tv_CFInterval)
    TextView tv_CFInterval;
    @BindView(R.id.rel_CFInterval)
    RelativeLayout rel_CFInterval;
    @BindView(R.id.sg_blood)
    ScrollGridView sg_blood;
    @BindView(R.id.rel_blood)
    RelativeLayout rel_blood;
    @BindView(R.id.img_more)
    ImageView img_more;
    private EditText ed_value;

    private ApiService service;
    private BloodTimeAdapter bloodTimeAdapter;
    private List<BloodTimeModel> listBloodTime = new ArrayList<>();
    private String programmed = "-1";
    private boolean isShown = false;
    private Dialog dialog;
    private RecyclerView recycleView;
    private MTXDurationAdapter mtxurationAdapter;
    private List<PerfusionIntervalModel> perfusionIntervalModels = new ArrayList<>();
    private PerfusionIntervalModel select_perfusion;

    private CFDurationAdapter cfdurationAdapter;
    private List<CFIntervalModel> cfIntervalModels = new ArrayList<>();
    private CFIntervalModel select_cf;
    private ContactModel contactModel;
    private int type;//0:编辑 1：新增
    private PrescriptionInfoModel prescriptionInfoModel;
    private String patientId;
    private String programmeId;
    private String prescriptionId;
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable edt) {
            String temp = edt.toString();
            int posDot = temp.indexOf(".");
            if (posDot <= 0) return;
            if (temp.length() - posDot - 1 > 1) {
                edt.delete(posDot + 2, posDot + 3);
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_new_prescription;
    }

    @Override
    public void initData() {
        Bundle bundle = this.getIntent().getExtras();
        type = bundle.getInt("type");
        if (type == 0) {
            prescriptionInfoModel = (PrescriptionInfoModel) bundle.getSerializable("prescriptionInfoModel");
            showData(prescriptionInfoModel);
        } else {
            programmed = bundle.getString("programmeId");
            if ("-1".equals(programmed)) {

            } else {
                showDialog("加载中");
                service.getDefaultProgrammeInfo(programmed)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .safeSubscribe(new Observer<ResponseData<DefaultPrescriptionModel>>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(ResponseData<DefaultPrescriptionModel> defaultPrescriptionModelResponseData) {
                                if (defaultPrescriptionModelResponseData != null) {
                                    int resultCode = defaultPrescriptionModelResponseData.getResultCode();
                                    if (resultCode == 200) {
                                        showData(defaultPrescriptionModelResponseData.getData());
                                    } else {
                                        showTextToast(defaultPrescriptionModelResponseData.getMessage());
                                    }
                                } else {
                                    showTextToast("请求失败");
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                disMiss();
                                showTextToast(RequestApi.detailError(e));
                            }

                            @Override
                            public void onComplete() {
                                disMiss();
                            }
                        });
            }
        }
    }

    private void showData(PrescriptionInfoModel prescriptionInfoModel) {
        PrescriptionInfoDetailModel prescriptionInfo = prescriptionInfoModel.getPrescriptionInfo();
        tv_MTXdose.setText(prescriptionInfo.getMTXdose());
        tv_MTXDuration.setText(prescriptionInfo.getMTXTimeDuration());
        tv_CFdose.setText(prescriptionInfo.getCFdose());
        tv_CFInterval.setText(prescriptionInfo.getCFTimeInterval());
        listBloodTime = prescriptionInfoModel.getListBloodTime();
        bloodTimeAdapter = new BloodTimeAdapter(listBloodTime, this);
        sg_blood.setAdapter(bloodTimeAdapter);
        isShown = true;
        sg_blood.setVisibility(View.VISIBLE);

        programmeId = prescriptionInfo.getProgrammeId();
        prescriptionId = prescriptionInfo.getPrescriptionId();
        patientId = prescriptionInfo.getPatientId();
        tv_patient_name.setText(prescriptionInfo.getPatientName());
        if ("0".equals(prescriptionInfo.getPatientName())) {
            tv_patient_sex.setText("女");
        } else {
            tv_patient_sex.setText("男");
        }
        tv_patient_bed_no.setText(prescriptionInfo.getPatientBedNumber());
        tv_patient_history.setText(prescriptionInfo.getPatientCondition());
        tv_patient_age.setText(prescriptionInfo.getPatientAge());
        tv_patient_weight.setText(prescriptionInfo.getPatientWeight());
        tv_patient_height.setText(prescriptionInfo.getPatientHeight());

    }

    private void showData(DefaultPrescriptionModel defaultPrescriptionModel) {
        ProgrammeInfoModel programmeInfo = defaultPrescriptionModel.getProgrammeInfo();
        tv_MTXdose.setText(programmeInfo.getMTXdose());
        tv_MTXDuration.setText(programmeInfo.getMTXDuration());
        tv_CFdose.setText(programmeInfo.getCFdose());
        tv_CFInterval.setText(programmeInfo.getCFInterval());
        listBloodTime = defaultPrescriptionModel.getListBloodTime();
        bloodTimeAdapter = new BloodTimeAdapter(listBloodTime, this);
        sg_blood.setAdapter(bloodTimeAdapter);
        isShown = true;
        sg_blood.setVisibility(View.VISIBLE);
    }

    @Override
    public void initView() {
        service = RequestApi.create(ApiService.class);
        //setStatus(true);
        tv_title.setText("健康处方");
        tv_right.setText("提交");
        rel_right.setVisibility(View.VISIBLE);
        rel_left.setOnClickListener(this);
        rel_right.setOnClickListener(this);
        tv_choose_patient.setOnClickListener(this);
        rel_blood.setOnClickListener(this);
        rel_MTXDuration.setOnClickListener(this);
        rel_CFInterval.setOnClickListener(this);
        rel_CFdose.setOnClickListener(this);
        rel_MTXdose.setOnClickListener(this);
        sg_blood.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BloodTimeModel bloodTimeModel = listBloodTime.get(position);
                if ("0".equals(bloodTimeModel.getBloodIsSelect())) {
                    bloodTimeModel.setBloodIsSelect("1");
                } else {
                    bloodTimeModel.setBloodIsSelect("0");
                }
                listBloodTime.set(position, bloodTimeModel);
                bloodTimeAdapter.notifyDataSetChanged();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (requestCode == 101 && data != null) {
            contactModel = (ContactModel) data.getSerializableExtra("account");
            patientId = contactModel.getPatientId();
            tv_patient_name.setText(contactModel.getPatientName());
            if ("0".equals(contactModel.getPatientName())) {
                tv_patient_sex.setText("女");
            } else {
                tv_patient_sex.setText("男");
            }
            tv_patient_bed_no.setText(contactModel.getPatientBedNumber());
            tv_patient_history.setText(contactModel.getPatientCondition());
            tv_patient_age.setText(contactModel.getPatientAge());
            tv_patient_weight.setText(contactModel.getPatientWeight());
            tv_patient_height.setText(contactModel.getPatientHeight());
        }
    }

    private void showcfDoseDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View customView = inflater.inflate(R.layout.dia_edit, null);
        dialog = new Dialog(this);
        dialog.setContentView(customView);
        dialog.show();
        TextView tv = (TextView) customView.findViewById(R.id.tv_title);
        TextView tv_confirm = (TextView) customView.findViewById(R.id.tv_confirm);
        ed_value = (EditText) customView.findViewById(R.id.ed_value);
        ed_value.addTextChangedListener(textWatcher);
        ed_value.setText(tv_CFdose.getText());
        tv.setText("CF解救剂量");
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String value=ed_value.getText().toString();
                if(!TextUtils.isEmpty(value)){
                    if(value.contains(".")){
                        String[] split = value.split("\\.");
                        if(split.length<=1){
                            showTextToast("输入数据非法，请重新输入");
                            return;
                        }
                        if(split.length==2){
                            if(TextUtils.isEmpty(split[0])){
                                showTextToast("输入数据非法，请重新输入");
                                return;
                            }
                        }
                    }
                }
                tv_CFdose.setText(value);
                dialog.dismiss();
            }
        });
    }

    private void showMTXDoseDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View customView = inflater.inflate(R.layout.dia_edit, null);
        dialog = new Dialog(this);
        dialog.setContentView(customView);
        dialog.show();
        TextView tv = (TextView) customView.findViewById(R.id.tv_title);
        TextView tv_confirm = (TextView) customView.findViewById(R.id.tv_confirm);
        final EditText ed_value = (EditText) customView.findViewById(R.id.ed_value);
        ed_value.addTextChangedListener(textWatcher);
        ed_value.setText(tv_MTXdose.getText());
        tv.setText("MTX灌注剂量");
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String value=ed_value.getText().toString();
                if(!TextUtils.isEmpty(value)){
                    if(value.contains(".")){
                        String[] split = value.split("\\.");
                        if(split.length<=1){
                            showTextToast("输入数据非法，请重新输入");
                            return;
                        }
                        if(split.length==2){
                            if(TextUtils.isEmpty(split[0])){
                                showTextToast("输入数据非法，请重新输入");
                                return;
                            }
                        }
                    }
                }
                tv_MTXdose.setText(value);
                dialog.dismiss();
            }
        });
    }

    private void showcfDurationDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View customView = inflater.inflate(R.layout.dia_choose_list, null);
        dialog = new Dialog(this);
        dialog.setContentView(customView);
        dialog.show();
        recycleView = (RecyclerView) customView.findViewById(R.id.recy);
        TextView tv = (TextView) customView.findViewById(R.id.tv_title);
        TextView tv_confirm = (TextView) customView.findViewById(R.id.tv_confirm);
        ed_value = (EditText) customView.findViewById(R.id.ed_value);
        ed_value.addTextChangedListener(textWatcher);
        ed_value.setText(tv_CFInterval.getText());
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String value=ed_value.getText().toString();
                if(!TextUtils.isEmpty(value)){
                    if(value.contains(".")){
                        String[] split = value.split("\\.");
                        if(split.length<=1){
                            showTextToast("输入数据非法，请重新输入");
                            return;
                        }
                        if(split.length==2){
                            if(TextUtils.isEmpty(split[0])){
                                showTextToast("输入数据非法，请重新输入");
                                return;
                            }
                        }
                    }
                }
                tv_CFInterval.setText(value);
                dialog.dismiss();
            }
        });
        tv.setText("请选择解救时间(h)");
        setcfDurationAdapter();
    }

    /**
     * 设置adapter
     */
    public void setcfDurationAdapter() {
        cfdurationAdapter = new CFDurationAdapter(R.layout.item_choose, cfIntervalModels, select_cf);
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        cfdurationAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recycleView.setAdapter(cfdurationAdapter);
        recycleView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                CFIntervalModel cfIntervalModel = cfdurationAdapter.getData().get(i);
                select_cf = cfIntervalModel;
                ed_value.setText(cfIntervalModel.getRescueIntervalValue());
            }
        });
    }

    private void getBloodIntervalList() {
        showDialog("加载中");
        service.getBloodIntervalList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<BloodIntervalListModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<BloodIntervalListModel> bloodIntervalListModelResponseData) {
                        if (bloodIntervalListModelResponseData != null) {
                            int resultCode = bloodIntervalListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                listBloodTime = bloodIntervalListModelResponseData.getData().getBloodIntervalList();
                                for (int i = 0; i < listBloodTime.size(); i++) {
                                    BloodTimeModel bloodTimeModel = listBloodTime.get(i);
                                    bloodTimeModel.setBloodIsSelect("0");
                                }
                                bloodTimeAdapter = new BloodTimeAdapter(listBloodTime, NewPrescriptionActivity.this);
                                sg_blood.setAdapter(bloodTimeAdapter);
                                isShown = true;
                                sg_blood.setVisibility(View.VISIBLE);
                            } else {
                                showTextToast(bloodIntervalListModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }

    private void getcfIntervalList() {
        showDialog("加载中");
        service.getRescueIntervalList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<CFIntervalListModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<CFIntervalListModel> cfIntervalListModelResponseData) {
                        if (cfIntervalListModelResponseData != null) {
                            int resultCode = cfIntervalListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                cfIntervalModels = cfIntervalListModelResponseData.getData().getRescueIntervalList();
                                showcfDurationDialog();
                            } else {
                                showTextToast(cfIntervalListModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }


    private void showMTXDurationDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View customView = inflater.inflate(R.layout.dia_choose_list, null);
        dialog = new Dialog(this);
        dialog.setContentView(customView);
        dialog.show();
        recycleView = (RecyclerView) customView.findViewById(R.id.recy);
        TextView tv = (TextView) customView.findViewById(R.id.tv_title);
        TextView tv_confirm = (TextView) customView.findViewById(R.id.tv_confirm);
        ed_value = (EditText) customView.findViewById(R.id.ed_value);
        ed_value.addTextChangedListener(textWatcher);
        ed_value.setText(tv_MTXDuration.getText());
        tv.setText("请选择灌注时间(h)");
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String value=ed_value.getText().toString();
                if(!TextUtils.isEmpty(value)){
                    if(value.contains(".")){
                        String[] split = value.split("\\.");
                        if(split.length<=1){
                            showTextToast("输入数据非法，请重新输入");
                            return;
                        }
                        if(split.length==2){
                            if(TextUtils.isEmpty(split[0])){
                                showTextToast("输入数据非法，请重新输入");
                                return;
                            }
                        }
                    }
                }
                tv_MTXDuration.setText(value);
                dialog.dismiss();
            }
        });
        setMTXDurationAdapter();
    }

    /**
     * 设置adapter
     */
    public void setMTXDurationAdapter() {
        mtxurationAdapter = new MTXDurationAdapter(R.layout.item_choose, perfusionIntervalModels, select_perfusion);
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        mtxurationAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recycleView.setAdapter(mtxurationAdapter);
        recycleView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                PerfusionIntervalModel perfusionIntervalModel = mtxurationAdapter.getData().get(i);
                select_perfusion = perfusionIntervalModel;
                ed_value.setText(select_perfusion.getPerfusionIntervalValue());
            }
        });
    }

    private boolean checkValue() {
        if (TextUtils.isEmpty(patientId)) {
            showTextToast("请先选择病人");
            return false;
        }
        if (TextUtils.isEmpty(tv_MTXdose.getText())) {
            showTextToast("请先设置MTX灌注剂量");
            return false;
        }
        if (TextUtils.isEmpty(tv_MTXDuration.getText())) {
            showTextToast("请先设置MTX灌注时间");
            return false;
        }
        if (TextUtils.isEmpty(tv_CFdose.getText())) {
            showTextToast("请先设置CF解救剂量");
            return false;
        }
        if (TextUtils.isEmpty(tv_CFInterval.getText())) {
            showTextToast("请先设置CF解救时间");
            return false;
        }
        if (listBloodTime.size() == 0) {
            showTextToast("请先设置采血时间");
            return false;
        }
        int has_blood = 0;
        for (int i = 0; i < listBloodTime.size(); i++) {
            BloodTimeModel bloodTimeModel = listBloodTime.get(i);
            if ("1".equals(bloodTimeModel.getBloodIsSelect())) {
                has_blood++;
            }
        }
        if (has_blood == 0) {
            showTextToast("请先设置采血时间");
            return false;
        }
        return true;
    }

    private void addNewPrescription() {
        if (checkValue()) {
            showDialog("加载中");
            UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
            String userId = userModel.getUserId();
            AddNewPrescriptionRequestModel addNewPrescriptionRequestModel = new AddNewPrescriptionRequestModel();
            addNewPrescriptionRequestModel.setListBloodTime(listBloodTime);
            addNewPrescriptionRequestModel.setUserId(userId);
            addNewPrescriptionRequestModel.setPatientId(contactModel.getPatientId());
            addNewPrescriptionRequestModel.setMTXdose(tv_MTXdose.getText().toString());
            addNewPrescriptionRequestModel.setMTXTimeDuration(tv_MTXDuration.getText().toString());
            addNewPrescriptionRequestModel.setCFdose(tv_CFdose.getText().toString());
            addNewPrescriptionRequestModel.setCFTimeInterval(tv_CFInterval.getText().toString());
            service.addNewPrescription(addNewPrescriptionRequestModel)
//            service.addNewPrescriptions("2", patientId, tv_MTXdose.getText().toString(), tv_MTXDuration.getText().toString()
//                    , tv_CFdose.getText().toString(), tv_CFInterval.getText().toString()
//                    , listBloodTime
//            )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .safeSubscribe(new Observer<ResponseData>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(ResponseData perfusionIntervalListModelResponseData) {
                            if (perfusionIntervalListModelResponseData != null) {
                                int resultCode = perfusionIntervalListModelResponseData.getResultCode();
                                if (resultCode == 200) {
                                    showTextToast("添加成功");
                                    finish();
                                } else {
                                    showTextToast(perfusionIntervalListModelResponseData.getMessage());
                                }
                            } else {
                                showTextToast("请求失败");
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            disMiss();
                            showTextToast(RequestApi.detailError(e));
                        }

                        @Override
                        public void onComplete() {
                            disMiss();
                        }
                    });
        }
    }

    private void editPrescription() {
        if (checkValue()) {
            showDialog("加载中");
            UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
            String userId = userModel.getUserId();
            EditPrescriptionRequestModel editPrescriptionRequestModel = new EditPrescriptionRequestModel();
            editPrescriptionRequestModel.setListBloodTime(listBloodTime);
            editPrescriptionRequestModel.setUserId(userId);
            editPrescriptionRequestModel.setPatientId(patientId);
            editPrescriptionRequestModel.setPrescriptionId(prescriptionId);
            editPrescriptionRequestModel.setProgrammeId(programmeId);
            editPrescriptionRequestModel.setMTXdose(tv_MTXdose.getText().toString());
            editPrescriptionRequestModel.setMTXTimeDuration(tv_MTXDuration.getText().toString());
            editPrescriptionRequestModel.setCFdose(tv_CFdose.getText().toString());
            editPrescriptionRequestModel.setCFTimeInterval(tv_CFInterval.getText().toString());
            service.editPrescription(editPrescriptionRequestModel)
//            service.editPrescriptions("2", programmeId, prescriptionId, patientId, tv_MTXdose.getText().toString(), tv_MTXDuration.getText().toString()
//                    , tv_CFdose.getText().toString(), tv_CFInterval.getText().toString()
//                    , listBloodTime
//            )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .safeSubscribe(new Observer<ResponseData>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(ResponseData perfusionIntervalListModelResponseData) {
                            if (perfusionIntervalListModelResponseData != null) {
                                int resultCode = perfusionIntervalListModelResponseData.getResultCode();
                                if (resultCode == 200) {
                                    showTextToast("编辑成功");
                                    setResult(2, getIntent());
                                    finish();
                                } else {
                                    showTextToast(perfusionIntervalListModelResponseData.getMessage());
                                }
                            } else {
                                showTextToast("请求失败");
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            disMiss();
                            showTextToast(RequestApi.detailError(e));
                        }

                        @Override
                        public void onComplete() {
                            disMiss();
                        }
                    });
        }
    }

    private void getPerfusionIntervalList() {
        showDialog("加载中");
        service.getPerfusionIntervalList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<PerfusionIntervalListModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<PerfusionIntervalListModel> perfusionIntervalListModelResponseData) {
                        if (perfusionIntervalListModelResponseData != null) {
                            int resultCode = perfusionIntervalListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                perfusionIntervalModels = perfusionIntervalListModelResponseData.getData().getPerfusionIntervalList();
                                showMTXDurationDialog();
                            } else {
                                showTextToast(perfusionIntervalListModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_CFdose:
                showcfDoseDialog();
                break;
            case R.id.rel_MTXdose:
                showMTXDoseDialog();
                break;
            case R.id.rel_CFInterval:
                if (cfIntervalModels.size() == 0) {
                    getcfIntervalList();
                } else {
                    showcfDurationDialog();
                }
                break;
            case R.id.rel_MTXDuration:
                if (perfusionIntervalModels.size() == 0) {
                    getPerfusionIntervalList();
                } else {
                    showMTXDurationDialog();
                }
                break;
            case R.id.rel_right:
                String value="";
                if (type == 0) {
                    value="确认修改该处方案例？";
                } else {
                    value="保存并另存为处方案例";
                }
                AlertDialog.Builder dialogBuilder_shop = new AlertDialog.Builder(this)
                        .setTitle("温馨提示")
                        .setMessage(value)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (type == 0) {
                                    editPrescription();
                                } else {
                                    addNewPrescription();
                                }
                            }
                        });

                dialogBuilder_shop.create().show();
                break;
            case R.id.rel_left:
                finish();
                break;
            case R.id.tv_choose_patient:
                startActivityForResult(PatientChooseActivity.class, 101);
                break;
            case R.id.rel_blood:
                if (!isShown) {
                    isShown = true;
                    Glide.with(this)
                            .load(R.drawable.img_client_report_more)
                            .into(img_more);
                    sg_blood.setVisibility(View.VISIBLE);
                } else {
                    isShown = false;
                    Glide.with(this)
                            .load(R.drawable.img_more)
                            .into(img_more);
                    sg_blood.setVisibility(View.GONE);
                }
                if ("-1".equals(programmed)) {
                    if (listBloodTime.size() == 0) {
                        getBloodIntervalList();
                    }
                }
                break;
        }
    }
}
